package vn.orderonline.com.core.business.temporaryorder;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vn.orderonline.com.core.business.dto.TemporaryFoodBasketDto;
import vn.orderonline.core.dao.entity.TemporaryFoodBasket;
import vn.orderonline.core.dao.entity.TemporaryFoodBasketId;
import vn.orderonline.core.dao.temporaryorder.TemporaryFoodBasketDao;

@Service
@Transactional
public class TemporaryFoodBasketImpl implements ITemporaryFoodBasket {
	
	@Autowired
	private TemporaryFoodBasketDao temporaryFoodBasketDao;

	@Override
	public void addFood(Integer restaurantId, Integer foodId, String foodName, Float price) {
		TemporaryFoodBasket temporaryFoodBasket = temporaryFoodBasketDao.find(new TemporaryFoodBasketId(restaurantId, foodId));
		if (temporaryFoodBasket != null) {
			temporaryFoodBasket.setAmount(temporaryFoodBasket.getAmount() + 1);
			temporaryFoodBasketDao.save(temporaryFoodBasket);
		} else {
			temporaryFoodBasket = new TemporaryFoodBasket();
			temporaryFoodBasket.setId(new TemporaryFoodBasketId(restaurantId, foodId));
			temporaryFoodBasket.setFoodName(foodName);
			temporaryFoodBasket.setPrice(price);
			temporaryFoodBasket.setAmount(1);
			temporaryFoodBasketDao.save(temporaryFoodBasket);
		}
	}

	@Override
	public List<TemporaryFoodBasketDto> getAllFoods() {
		List<TemporaryFoodBasket> listItem = temporaryFoodBasketDao.findAll();
		if (!listItem.isEmpty()) {
			List<TemporaryFoodBasketDto> list = new ArrayList<>();
			TemporaryFoodBasketDto dto = null;
			for (TemporaryFoodBasket tem : listItem) {
				dto = new TemporaryFoodBasketDto();
				dto.setRestaurantId(tem.getId().getRestaurantId());
				dto.setFoodId(tem.getId().getFoodId());
				dto.setFoodName(tem.getFoodName());
				dto.setPrice(tem.getPrice() * tem.getAmount());
				dto.setAmount(tem.getAmount());
				list.add(dto);
			}
			return list;
		}
		return null;
	}

	@Override
	public Float calculateFoodPrice() {
		List<TemporaryFoodBasket> list = temporaryFoodBasketDao.findAll();
		Float count = 0F;
		if (!list.isEmpty()) {
			for (TemporaryFoodBasket tem : list) {
				count += tem.getPrice() * tem.getAmount(); 
			}
		}
		return count;
	}

	@Override
	public void removeFoodBasket(Integer restaurantId, Integer foodId) {
		TemporaryFoodBasket temporaryFoodBasket = temporaryFoodBasketDao.find(new TemporaryFoodBasketId(restaurantId, foodId));
		if (temporaryFoodBasket != null) {
			if (temporaryFoodBasket.getAmount() > 1) {
				temporaryFoodBasket.setAmount(temporaryFoodBasket.getAmount() - 1);
				temporaryFoodBasketDao.save(temporaryFoodBasket);
			} else {
				temporaryFoodBasketDao.delete(temporaryFoodBasket);
			}
		}
		
	}

}
